package com.example.test.springdemo.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

/**
 * @author ：吉金武
 * @ClassName JWTUtils
 * @date ：2022/1/18 - 22:43
 * @version: V1.0
 * @slogan: 天下风云出我辈，一入代码岁月催
 * @description:
 **/
public class JWTUtils {

    private static final String SIGN= "8ba6cf3288b149109af825f33431aab3";

    /**
     * 生成token header.payload.sign
     */
    public static String getToken(Map<String,String> map){
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND,30*60*1000);

        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();
        //payload
        map.forEach((k,v)->{
                builder.withClaim(k,v);
        });
        String token = builder.withExpiresAt(instance.getTime()) //指定令牌的过期时间
                .sign(Algorithm.HMAC256(SIGN));//sign
        return token;
    }

    /**
     * 验证token 返回token信息
     */
    public static DecodedJWT verify(String token){
        return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }
}

